package com.zhentao.device.Controller;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws/water-quality")
public class WaterQualityWebSocket {
    private static final Set<Session> SESSIONS = ConcurrentHashMap.newKeySet();

    @OnOpen
    public void onOpen(Session session) {
        SESSIONS.add(session);
    }

    @OnClose
    public void onClose(Session session) {
        SESSIONS.remove(session);
    }

    @OnError
    public void onError(Session session, Throwable thr) {
        SESSIONS.remove(session);
    }

    public static void broadcast(double ph, double temperature, double turbidity) {
        JSONObject obj = new JSONObject();
        obj.put("phValue", roundOne(ph));
        obj.put("temperature", roundOne(temperature));
        obj.put("turbidity", roundOne(turbidity));
        String payload = obj.toJSONString();
        for (Session s : SESSIONS) {
            if (s.isOpen()) {
                try {
                    s.getBasicRemote().sendText(payload);
                } catch (IOException ignored) {}
            }
        }
    }

    private static double roundOne(double v) {
        return Math.round(v * 10.0) / 10.0;
    }
}


